<template>
  <el-container>
    <el-aside :width="isCollapse ? '64px' : '240px'" class="custom-aside">
      <div class="logo-container">
        <img src="https://tse2-mm.cn.bing.net/th/id/OIP-C.eBbeibCXZFkK9F6wnMHnNgHaG8?rs=1&pid=ImgDetMain" class="logo">
        <span v-show="!isCollapse" class="logo-text">智慧食堂</span>
      </div>

      <div class="menu-container">
        <el-menu @select="handleSelect" :default-active="activeTab" :collapse="isCollapse" class="aside-vertical-menu" 
          :collapse-transition="false" :unique-opened="true">

          <template v-for="(topMenu, index) in topMenuList">
            <!-- 迭代有二级子菜单的菜单 -->
            <el-sub-menu v-if="topMenu.children && topMenu.children.length" :key="index" :index="topMenu.name">
              <template #title>
                <el-icon><component :is="topMenu.meta.icon" /></el-icon>
                <span v-if="!isCollapse">{{ topMenu.meta.title }}</span>
              </template>
              <!-- 迭代二级子菜单 -->
              <el-menu-item v-for="child in topMenu.children" :key="child.name" :index="child.name">
                <el-icon><component :is="child.meta.icon" /></el-icon>
                <span>{{ child.meta.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 没有二级子菜单的菜单 -->
            <el-menu-item v-else="!topMenu.children && topMenu.meta" :key="index+1" :index="topMenu.name">
              <el-icon><component :is="topMenu.meta.icon" /></el-icon>
              <span>{{ topMenu.meta.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
    </el-aside>

    <el-container>
      <el-header>
        <el-row class="header-content">
          <el-col :span="2">
            <el-button @click="toggleAside">
              <el-icon color="rgb(56,18,110)" size="large"><component :is="toggleIcon" /></el-icon>
            </el-button>
          </el-col>
          <el-col :span="22" style="text-align: right;">
            <el-dropdown>
              <span class="el-dropdown-link">
                <span>欢迎你,</span>
                <span style="margin:0 8px;">{{ userInfo.username }}</span>
                <el-icon><CaretBottom /></el-icon>
                <el-avatar :size="60" :src="userInfo.avatar"/>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
      </el-header>

      <el-main>
        <el-tabs v-model="currentActiveTab" @tab-click="handleTabClick" type="card" closable @tab-remove="handleTabRemove">
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.name"
            :label="tab.title"
            :name="tab.name"
          >
            <div class="line"></div>
            <router-view v-slot="{ Component }" v-if="activeTab === tab.name">
              <transition name="move" mode="out-in">
                <keep-alive>
                  <component :is="Component"></component>
                </keep-alive>
              </transition>
            </router-view>
          </el-tab-pane>
        </el-tabs>
      </el-main>

      <el-footer>
        <el-text class="mx-1" type="info">Copyright &copy; 2024-2026  乐码君 版权所有</el-text>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTabsStore } from '@/store/tabs.js'
import { Fold, Expand, CaretBottom } from '@element-plus/icons-vue'

// 引入需要的 Element Plus 图标组件
const isCollapse = ref(false)
const toggleIcon = ref(Fold) // 初始为折叠图标
const tabsStore = useTabsStore()
const router = useRouter()
const route = useRoute()
const currentActiveTab = ref(tabsStore.activeTab)

const topMenuList = computed(() => router.getRoutes().filter(r => r.meta.top))

const handleSelect = (index) => {
  const menuRoute = topMenuList.value.find(r => r.name === index || r.children?.some(child => child.name === index))
  const childRoute = menuRoute?.children?.find(child => child.name === index)
  const selectedRoute = childRoute || menuRoute
  if (selectedRoute && selectedRoute.meta) {
    tabsStore.addTab({ title: selectedRoute.meta.title, name: selectedRoute.name })
    router.push({ name: selectedRoute.name })
  }
}

const toggleAside = () => {
  isCollapse.value = !isCollapse.value
  toggleIcon.value = isCollapse.value ? Expand : Fold
}

const activeTab = computed(() => tabsStore.activeTab)
router.push({ name: activeTab.value })
const tabs = computed(() => tabsStore.tabs)

const handleTabClick = (tab) => {
  tabsStore.setActiveTab(tab.props.name)
  router.push({ name: tab.props.name })
}

const handleTabRemove = (tabName) => {
  tabsStore.closeTab(tabName)
}

watch(tabs, (newTabs) => {
  localStorage.setItem('tabs', JSON.stringify(newTabs))
}, { deep: true })

watch(activeTab, (newActiveTab) => {
  localStorage.setItem('activeTab', newActiveTab)
  currentActiveTab.value = newActiveTab
})

watch(isCollapse, (newIsCollapse) => {
  localStorage.setItem('isCollapse', newIsCollapse)
})

onMounted(() => {
  const savedTabs = JSON.parse(localStorage.getItem('tabs'))
  const savedActiveTab = localStorage.getItem('activeTab')

  isCollapse.value = localStorage.getItem('isCollapse') === 'true'
  toggleIcon.value = isCollapse.value ? Expand : Fold

  if (savedTabs) {
    savedTabs.forEach(tab => {
      tabsStore.addTab(tab)
    })
  }
  
  if (savedActiveTab) {
    tabsStore.setActiveTab(savedActiveTab)
    currentActiveTab.value = savedActiveTab
    router.push({ name: savedActiveTab })
  }
})

const userInfo = reactive({
  avatar: '/src/assets/img/2.jfif',
  username: '管理员'
})

// const info = () => {
//   tabsStore.addTab({
//     name: 'Info',
//     title: '个人信息',
//   })
//   router.push({ name: 'Info' })
// }

const logout = () => {
  tabsStore.resetTabs()
  router.push({ name: 'Login' })
}

// 注册图标组件（在 setup 中通过 withDefaults 或直接使用）
defineExpose({
  Fold,
  Expand,
  CaretBottom
})
</script>

<style scoped>
/* 样式部分保持不变 */
.custom-aside {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #1a2a42;
  transition: width 0.3s ease;
}

.logo-container {
  padding: 8px;
  flex-shrink: 0;
  background-color: #152238;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.logo {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  display: inline;
}
.logo-text {
  font-size: 1.4em;
  font-weight: 700;
  color: rgb(255, 255, 255);
  margin-left: 15px;
}

.menu-container {
  flex: 1;
  overflow-y: auto;
}

.menu-container::-webkit-scrollbar {
  width: 6px;
}
.menu-container::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}
.menu-container::-webkit-scrollbar-track {
  background-color: transparent;
}

.aside-vertical-menu:not(.el-menu--collapse),
.el-menu--collapse {
  height: calc(100vh - 80px);
}

.aside-vertical-menu {
  background-color: #1a2a42 !important;
  --el-menu-bg-color: #1a2a42 !important;
  border-right: none;
  transition: height 0.3s ease;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  transition: all 0.3s ease;
  color: #a0aec0;
}

:deep(.el-menu-item):hover,
:deep(.el-sub-menu):hover .el-sub-menu__title {
  background-color: #2d3748 !important;
  color: #ffffff !important;
}

:deep(.el-menu-item).is-active,
:deep(.el-sub-menu).is-active .el-sub-menu__title {
  background-color: #2c5282 !important;
  color: #ffffff !important;
  border-left: 3px solid #4299e1;
}

.el-menu--collapse .el-sub-menu__title,
.el-menu--collapse .el-menu-item {
  display: flex;
  justify-content: center;
  padding: 0 5px !important;
}

.el-container {
  height: 100vh;
}

.el-header {
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #333;
  text-align: left;
  line-height: 60px;
}

.el-button {
  background-color: transparent !important;
  border: none !important;
  padding: 5px !important;
}


.el-dropdown-link {
  color: #4a5568;
}


:deep(.el-tabs__item) {
  color: #718096;
  border-radius: 4px 4px 0 0 !important;
  margin-right: 4px !important;
}
:deep(.el-tabs__item.is-active) {
  background-color: #ffffff !important;
  color: #2c5282 !important;
  border-bottom: 2px solid #2c5282 !important;
}
:deep(.el-tabs__item:hover){
  color: #2c5282 !important;
}

:deep(.el-tabs__header) {
  margin: 0 0 2px !important;
  background-color: #f7fafc;
  border-radius: 4px 4px 0 0;
}

.line {
  border: 1px solid #e2e8f0;
  margin-bottom: 15px;
}

.el-main {
  background-color: #f7fafc;
  padding: 20px !important;
}

.el-footer{
  height: 40px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e2e8f0;
  color: #718096;
}

.el-dropdown-link{
  display: inline-flex;
  align-items: center;
}
</style>